package com.test.base.controller;

import com.test.base.entity.User;
import com.test.utils.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ssang
 * @date 2021-12-09 15:51
 */
@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session){
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try{
            //比较验证码
            String codes = (String) session.getAttribute("code");
//            if (codes.equalsIgnoreCase(code)){
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
//            }
        }catch (UnknownAccountException e){
            //账号不存在
            System.out.println("账号不存在");
            return "register";
        }catch (IncorrectCredentialsException e){
            //密码不正确
            System.out.println("密码不正确");
            return "login";
        }
//        return "index";
        return "redirect:index.jsp";
    }

    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //验证码放入session
        session.setAttribute("code",code);
        //验证码存入图片
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
